@include ('user.header',['title'=>'用户中心'])

<div class="container mt-3">
  @if (session('status'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <strong>{{ session('status') }}</strong>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  @endif

  <div class="row">
    <div class="col-md-3 d-none d-md-block">
      <div class="list-group">
        <a href="/user/forward-list" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
          <div>
            <i class="bi bi-link-45deg"></i> 转发域名列表
          </div>
          <span class="badge bg-primary rounded-pill">{{$forword}}</span>
        </a>
        <a href="/user/domain-list" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
          <div>
            <i class="bi bi-globe"></i> 短网址域名列表
          </div>
          <span class="badge bg-primary rounded-pill">{{$domain}}</span>
        </a>
        <a href="/user/dwz-list" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
          <div>
            <i class="bi bi-link-45deg"></i> 短网址列表
          </div>
          <span class="badge bg-primary rounded-pill">{{$dwz}}</span>
        </a>
        <a href="/user/password-edit" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
          <div>
            <i class="bi bi-key-fill"></i> 修改密码
          </div>
        </a>
        <a href="#./user-email" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center" onclick="alert('暂时无法使用')">
          <div>
            <i class="bi bi-envelope-fill"></i> 更换邮箱
          </div>
        </a>
      </div>
    </div>
    <div class="col-md-9">
      <div class="card shadow-sm">
        <div class="card-header bg-success text-white">
          <h3 class="card-title mb-0">账户状态</h3>
        </div>
        <div class="card-body">
          <ul class="list-group list-group-flush">
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <div><i class="bi bi-cash-coin"></i> 当前余额</div>
              <div class="d-flex align-items-center">
                <strong>{{$user['balance'] ?? '0.00'}} 元</strong>
                <button type="button" class="btn btn-primary btn-sm ms-3" data-bs-toggle="modal" data-bs-target="#rechargeModal">
                  <i class="bi bi-plus-circle"></i> 充值
                </button>
              </div>
            </li>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <div><i class="bi bi-arrow-repeat"></i> 转发额度</div>
              <strong>{{$user['forward'] ?? '∞'}}个</strong>
            </li>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <div><i class="bi bi-globe"></i> 域名额度</div>
              <strong>{{$user['dwz'] ?? '∞'}}个</strong>
            </li>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <div><i class="bi bi-award"></i> 会员等级</div>
              <div class="d-flex flex-column align-items-end">
                <div class="d-flex align-items-center">
                  <span class="badge bg-primary text-white fs-6 me-3">{{$vip['name']}}</span>
                  @if($vips->count() != 0)
                
                  <button type="button" class="btn btn-outline-primary btn-sm me-2" data-bs-toggle="modal" data-bs-target="#upgradeModal">
                    <i class="bi bi-arrow-up-circle"></i> 升级
                  </button>
                  
                @endif
                </div>
              </div>
            </li>
            <!-- 新增: 余额兑换转发额度 -->
            <li class="list-group-item">
              <div class="d-flex justify-content-between align-items-center">
                <div><i class="bi bi-arrow-repeat"></i> 兑换转发额度 <span class="text-muted">{{$vip['forward']}}元/个</span></div>
                <div class="d-flex align-items-center">
                  <input type="number" id="forwardQuantity" class="form-control me-2" value="1" placeholder="数量" required style="width: 100px;">
                  <button type="button" class="btn btn-success btn-sm" onclick="confirmExchange('forward')">兑换</button>
                </div>
              </div>
            </li>
            <!-- 新增: 余额兑换域名额度 -->
            <li class="list-group-item">
              <div class="d-flex justify-content-between align-items-center">
                <div><i class="bi bi-globe"></i> 兑换域名额度 <span class="text-muted">{{$vip['dwz']}}元/个</span></div>
                <div class="d-flex align-items-center">
                  <input type="number" id="domainQuantity" class="form-control me-2" value="1" placeholder="数量" required style="width: 100px;">
                  <button type="button" class="btn btn-success btn-sm" onclick="confirmExchange('domain')">兑换</button>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
      
      <div class="card shadow-sm mt-4">
        <div class="card-header bg-primary text-white">
          <h3 class="card-title mb-0">用户信息</h3>
        </div>
        <div class="card-body">
          <ul class="list-group list-group-flush">
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <div>
                <i class="bi bi-envelope-fill"></i> 帐户邮箱
              </div>
              <div>
                <strong>{{$user['email']}}</strong>
              </div>
            </li>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <div>
                <i class="bi bi-person-fill"></i> 帐户ＩＤ
              </div>
              <div>
                <strong>{{$user['id']}}</strong>
              </div>
            </li>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <div>
                <i class="bi bi-clock-fill"></i> 注册时间
              </div>
              <div>
                <strong>{{$user['created_at']}}</strong>
              </div>
            </li>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <div>
                <i class="bi bi-check-circle-fill"></i> 用户状态
              </div>
              <div>
                <strong>{{$user['status']?'正常':'禁用'}}</strong>
              </div>
            </li>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <div>
                <i class="bi bi-link-45deg"></i> 转发域名
              </div>
              <div>
                <strong>{{$forword}}个</strong>
              </div>
            </li>
          </ul>
        </div>
      </div>

      <!-- 新增: 充值弹窗模态框 -->
      <div class="modal fade" id="rechargeModal" tabindex="-1" aria-labelledby="rechargeModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <form action="/pay/epay" method="POST">
            @csrf
            <input type="hidden" name="userId" value="{{$user['id']}}">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="rechargeModalLabel">余额充值</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <div class="modal-body">
                <div class="mb-3">
                  <label for="rmb" class="form-label">充值金额</label>
                  <input type="number" class="form-control" id="rmb" name="amount" min="0.01" step="0.01" value="10" required>
                </div>
                <div class="mb-3">
                  <label class="form-label">支付通道</label>
                  <div class="d-flex flex-wrap gap-3">
                    @if(admin_setting('ypay_alipay_enable', 0)==1)
                      <div class="form-check">
                        <input class="form-check-input" type="radio" name="payway" id="alipay" value="alipay" required checked>
                        <label class="form-check-label" for="alipay">
                          <i class="bi bi-alipay text-primary me-1"></i>支付宝
                        </label>
                      </div>
                    @endif
                    @if(admin_setting('ypay_wechat_enable', 0)==1)
                      <div class="form-check">
                        <input class="form-check-input" type="radio" name="payway" id="wechat" value="wxpay" required>
                        <label class="form-check-label" for="wechat">
                          <i class="bi bi-wechat text-success me-1"></i>微信
                        </label>
                      </div>
                    @endif
                    @if(admin_setting('ypay_qq_enable', 0)==1)
                      <div class="form-check">
                        <input class="form-check-input" type="radio" name="payway" id="qqpay" value="qqpay" required>
                        <label class="form-check-label" for="qq">
                          <i class="bi bi-qq text-info me-1"></i>QQ钱包
                        </label>
                      </div>
                    @endif
                  </div>
                </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="submit" class="btn btn-primary">立即充值</button>
              </div>
            </div>
          </form>
        </div>
      </div>

      <!-- 新增: 会员升级模态框 -->
      <div class="modal fade" id="upgradeModal" tabindex="-1" aria-labelledby="upgradeModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="upgradeModalLabel">会员等级升级</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <div class="row g-4">
                @foreach($vips as $key => $v) 
                  <div class="col-md-6">
                    @php
                      $colors = ['primary', 'success', 'info', 'warning'];
                      $color = $colors[$key % count($colors)];
                    @endphp
                    <div class="card h-100 border-{{$color}} border-3 shadow-sm hover-shadow transition" style="cursor:pointer;" onclick="selectVip({{$key+1}})">
                      <div class="card-header bg-{{$color}} text-white">
                        <div class="d-flex align-items-center">
                          <input class="form-check-input me-2" type="radio" name="vip_id" id="vip{{$v['id']}}" value="{{$v['id']}}" required>
                          <label class="form-check-label fw-bold fs-5" for="vip{{$v['id']}}">{{$v['name']}}</label>
                        </div>
                      </div>
                      <div class="card-body">
                        {!!$v['data']!!}
                        <div class="d-flex justify-content-between align-items-center mt-auto">
                          <span class="badge bg-{{$color}}-subtle text-{{$color}} fs-6">￥{{$v['price']}}</span>
                          <button class="btn btn-{{$color}} btn-sm px-3" onclick="upgradeMembership({{$v['id']}})">立即升级</button>
                        </div>
                      </div>
                    </div>
                  </div>
                @endforeach
                @if($vips->count() == 0)
                你以升级到顶级
                @endif
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 新增: 会员续费模态框 -->
      <div class="modal fade" id="renewModal" tabindex="-1" aria-labelledby="renewModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <form action="/api/xf" method="POST">
            @csrf
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="renewModalLabel">会员续费</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <div class="modal-body">
                <div class="mb-3">
                  <label class="form-label">当前会员等级</label>
                  <input type="text" class="form-control" value="{{$user['membership_level']}}" readonly>
                </div>
                <div class="mb-3">
                  <label class="form-label">当前到期时间</label>
                  <input type="text" class="form-control" value="{{$user['membership_expiry'] ?? '无'}}" readonly>
                </div>
                <div class="mb-3">
                  <label class="form-label">选择续费时长</label>
                  <select class="form-select" name="duration" required>
                    <option value="">请选择</option>
                    <option value="3">3个月</option>
                    <option value="6">6个月</option>
                    <option value="12">12个月</option>
                  </select>
                </div>
                <input type="hidden" name="vip_id" value="{{$user['membership_level_id'] ?? ''}}">
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="submit" class="btn btn-primary">确认续费</button>
              </div>
            </div>
          </form>
        </div>
      </div>

      <!-- 新增: 通用确认模态框 -->
      <div class="modal fade" id="confirmModal" tabindex="-1" aria-labelledby="confirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="confirmModalLabel">确认操作</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <p id="confirmMessage">确定要执行此操作吗？</p>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-primary" id="confirmActionBtn">确认</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  // 新增: 兑换确认函数
  function confirmExchange(type) {
    let quantity, pricePerUnit, itemName;
    if (type === 'forward') {
      quantity = document.getElementById('forwardQuantity').value;
      pricePerUnit = {{$vip['forward'] ?? 0}};
      itemName = '转发额度';
    } else {
      quantity = document.getElementById('domainQuantity').value;
      pricePerUnit = {{$vip['dwz'] ?? 0}};
      itemName = '域名额度';
    }
    
    if (quantity <= 0) {
      alert('请输入有效数量');
      return;
    }
    
    const totalCost = quantity * pricePerUnit;
    document.getElementById('confirmMessage').textContent = `确定要兑换${quantity}个${itemName}吗？费用为${totalCost}元`;
    
    const confirmModal = new bootstrap.Modal(document.getElementById('confirmModal'));
    const confirmBtn = document.getElementById('confirmActionBtn');
    
    // 重置点击事件
    const newBtn = confirmBtn.cloneNode(true);
    confirmBtn.parentNode.replaceChild(newBtn, confirmBtn);
    
    newBtn.onclick = function() {
      if (type === 'forward') {
        exchangeForward();
      } else {
        exchangeDomain();
      }
    };
    
    confirmModal.show();
  }

  // 新增: 升级确认函数
  function confirmUpgrade(vipId) {
    // 获取对应VIP信息
    const vips = @json($vips);
    const vip = vips.find(v => v.id === vipId);
    if (!vip) {
      alert('未找到会员等级信息');
      return;
    }
    
    document.getElementById('confirmMessage').textContent = `确定要升级到【${vip.name}】吗？费用为${vip.price}元`;
    
    const confirmModal = new bootstrap.Modal(document.getElementById('confirmModal'));
    const confirmBtn = document.getElementById('confirmActionBtn');
    
    // 重置点击事件
    const newBtn = confirmBtn.cloneNode(true);
    confirmBtn.parentNode.replaceChild(newBtn, confirmBtn);
    
    newBtn.onclick = function() {
      upgradeMembership(vipId);
    };
    
    confirmModal.show();
  }

  // 提交兑换转发额度
  function exchangeForward() {
    const quantity = document.getElementById('forwardQuantity').value;
    const formData = new FormData();
    formData.append('_token', '{{ csrf_token() }}');
    formData.append('api_token', '{{$user['api_token']}}');
    formData.append('type', 'forward');
    formData.append('quantity', quantity);

    fetch('/api/user/forward/exchange', {
      method: 'POST',
      body: formData
    })
    .then(response => response.json())
    .then(data => {
      if (data.status === "0") {
        alert(data.msg); // 显示错误信息
      } else {
        alert('兑换成功！');
        location.reload(); // 刷新页面
      }
    })
    .catch(error => {
      console.error('Error:', error);
      alert('发生错误，请稍后再试。');
    });
  }

  // 提交兑换域名额度
  function exchangeDomain() {
    const quantity = document.getElementById('domainQuantity').value;
    const formData = new FormData();
    formData.append('_token', '{{ csrf_token() }}');
    formData.append('api_token', '{{$user['api_token']}}');
    formData.append('type', 'domain');
    formData.append('quantity', quantity);

    fetch('/api/user/dwz/exchange', {
      method: 'POST',
      body: formData
    })
    .then(response => response.json())
    .then(data => {
      if (data.status === "0") {
        alert(data.msg); // 显示错误信息
      } else {
        alert('兑换成功！');
        location.reload(); // 刷新页面
      }
    })
    .catch(error => {
      console.error('Error:', error);
      alert('发生错误，请稍后再试。');
    });
  }

  // 提交会员升级
  function upgradeMembership(vipId) {
    const formData = new FormData();
    formData.append('_token', '{{ csrf_token() }}');
    formData.append('api_token', '{{$user['api_token']}}');
    formData.append('vip_id', vipId);

    fetch('/api/user/vip/Upgrade', {
      method: 'POST',
      body: formData
    })
    .then(response => response.json())
    .then(data => {
      if (data.status === "0") {
        alert(data.msg); // 显示错误信息
      } else {
        alert('升级成功！');
        location.reload(); // 刷新页面
      }
    })
    .catch(error => {
      console.error('Error:', error);
      alert('发生错误，请稍后再试。');
    });
  }
</script>

@include ('user.footer')